import CryptoJS from "crypto-js";

let publicKey:any = "gKsz8+1m3HWvRAz+6tI7U8dxe+me0fvvj+Qz1MsjqQg=";
let ivKey:any ="gKsz8+1m3HWvRAz+6tI7U8dxe+me0fvvj+Qz1MsjqQg=";

const decryptECB = (encryptData: any) => {
  var key = CryptoJS.enc.Utf8.parse("cryptos-js-tests")
  var decrypt = CryptoJS.AES.decrypt(encryptData, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

const encryptECB = (encryptData: any) => {
  var key = CryptoJS.enc.Utf8.parse("cryptos-js-tests")
  var srcs = CryptoJS.enc.Utf8.parse(encryptData)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

export const encrypt = (word:any, keyStr?:any, ivStr?:any) => {
  if(localStorage.getItem('enc')){
    publicKey = localStorage.getItem('enc')
  }
  keyStr = keyStr ? keyStr : publicKey;
  ivStr = ivStr ? ivStr : ivKey;
  keyStr = decryptECB(keyStr)
  ivStr = decryptECB(ivStr)
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  let iv = CryptoJS.enc.Utf8.parse(ivStr);

  let words = CryptoJS.enc.Utf8.parse(word);
  var encrypt = CryptoJS.AES.encrypt(words, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Base64.stringify(encrypt.ciphertext);
}

export const decrypt = (word:any, keyStr?:any, ivStr?:any) => {
  if(localStorage.getItem('enc')){
    publicKey = localStorage.getItem('enc')
  }
  keyStr = keyStr ? keyStr : publicKey;
  ivStr = ivStr ? ivStr : ivKey;
  keyStr = decryptECB(keyStr)
  ivStr = decryptECB(ivStr)
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  let iv = CryptoJS.enc.Utf8.parse(ivStr);

  let base64 = CryptoJS.enc.Base64.parse(word);
  let src = CryptoJS.enc.Base64.stringify(base64)

  var decrypts = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypts).toString();
}

export const dealKeys = (publicKeys:any) => {
  var key = encryptECB(publicKeys)
  localStorage.setItem('enc', key)
  publicKey = key
}
